package cn.com.surker.system.service.impl;

import cn.com.surker.common.AESCoder;
import cn.com.surker.common.Code;
import cn.com.surker.common.Constant;
import cn.com.surker.enums.StateEnum;
import cn.com.surker.redis.RedisUtils;
import cn.com.surker.system.dao.*;
import cn.com.surker.system.entity.SysOrgPosition;
import cn.com.surker.system.entity.SysOriginRole;
import cn.com.surker.system.entity.SysUser;
import cn.com.surker.system.entity.SysUserPosition;
import cn.com.surker.system.service.UserService;
import cn.com.surker.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author lucky
 * @create 2022年06月24 10:14
 * @desc
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private SysUserDao userDao;

    /**用户部门角色表**/
    @Resource
    private SysOriginRoleDao originRoleDao;

    /**角色信息**/
    @Resource
    private SysRoleDao roleDao;

    /**redis缓存工具**/
    @Resource
    private RedisUtils redisUtils;

    /**站点日志登录接口**/
    @Resource
    private SysStationLogDao stationLogDao;

    /**数据源dao**/
    @Resource
    private DataSourceInfoDao dsDao;

//    @Autowired
//    @Qualifier("oaMysqlJdbcTemplate")
//    private JdbcTemplate oaJdbcTemplate;

    @Resource
    private SysUserPositionDao userPositionDao;
	@Resource
	private SysOrgPositionDao orgPositionDao;

    /**
     * 根据ID查询用户
     * @param uid
     * @return
     */
    public SysUser findById(Long uid) {
        if (StringUtils.isNull(uid))
            return null;

        SysUser user = userDao.selectById(uid);
        if (user == null || user.getStatus() == StateEnum.DISABLED.getCode())
            return null;
        return user;
    }

    /**
     * 更新数据
     * @param
     * @return
     */
    public Integer update(String openid, String unionid, String phone, String sessionKey) {
        if (StringUtils.isNull(phone))
            return Code.PARAM_ERROR.getCode();
        if (StringUtils.isNull(openid))
            openid = "";
        if (StringUtils.isNull(unionid))
            unionid = "";
        if (StringUtils.isNull(sessionKey))
            sessionKey = "";

        QueryWrapper<SysUser> query = new QueryWrapper<SysUser>();
        query.eq("status", StateEnum.ENABLED.getCode());
        query.eq("phone", phone);

        SysUser user = userDao.selectOne(query);
        if (user != null) {
            user.setOpenid(openid);
            user.setUnionid(unionid);
            user.setSessionKey(sessionKey);
            int code = userDao.updateById(user);
            if (code > 0)
                return 0;
            else
                return -1;
        }
        return Code.UN_USER_INFO.getCode();
    }

    /**
     * 根据Openid 手机号 账号查询用户
     * @param searchVal
     * @return
     */
    public SysUser queryUser(String searchVal) {
        if (StringUtils.isNull(searchVal))
            return null;

        QueryWrapper<SysUser> query = new QueryWrapper<SysUser>();
        query.eq("status", StateEnum.ENABLED.getCode());
        query.and(sysUserQueryWrapper -> sysUserQueryWrapper.eq("username", searchVal).or()
                .eq("phone", searchVal).or().eq("openid", searchVal).or().eq("card_no",searchVal));
        List<SysUser> list = userDao.selectList(query);
        if (list == null || list.size() == 0)
            return null;

        return list.get(0);
    }

    /**
     * 同步ERP账号
     * @param orgId
     * @return
     */
    public Integer synToErpAccount(Long orgId, String phone) {
//        String sql = "select a.id,a.login_name username,a.phone_num phone,a.ep_email email,a.name,a.status,b.id_card card,b.sex  \n" +
//                " from sys_user a RIGHT JOIN (select * from sys_person where status = 0 and id in (\n" +
//                " select DISTINCT person_id from sys_position_person where dept_id in (\n" +
//                " select id from sys_org where parent_id in (\n" +
//                " select id from sys_org where parent_id = " + orgId + ") or parent_id = " + orgId + " or id = "
//                + orgId + "))) b on a.phone_num = b.phone_number \n" +
//                " where a.status = 1 and a.id > 0 ";
//        if (!StringUtils.isNull(phone))
//            sql += " and a.phone_num = '" + phone + "'";
//        List<Map<String, Object>> list = oaJdbcTemplate.queryForList(sql);
//        if (list == null || list.size() == 0)
//        /**未获取到OA通讯录信息**/
//            return Code.UN_USER_BOOK.getCode();
//
//        DataSourceInfo ds = dsDao.queryDSByOriginId(orgId);
//        if (ds == null)
//            return -1;
//
//        /**获取数据库联系信息**/
//        JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
////        jdbcTemplate.execute("disable trigger Sys_User_T_Update on Sys_User_T");
////        String updateSql1 = "update sys_user_t set status = 1 where LoginName not in ('Master', 'Admin')";
////        jdbcTemplate.update(updateSql1);
////        jdbcTemplate.execute("enable trigger Sys_User_T_Update on Sys_User_T");
//        for (int i = 0; i < list.size(); i++) {
//            Map<String, Object> map = list.get(i);
//            String tempPhone = StringUtils.convertString(map.get("phone"));//手机号
//            String name = StringUtils.convertString(map.get("name"));//姓名
//            String card = StringUtils.convertString(map.get("card"));//身份证号
//            String password = AESCoder.md5(card.substring(card.length() - 6)).substring(8,24).toUpperCase();
//            Integer sex = StringUtils.convertInteger(map.get("sex"));
//            if (sex == 0)
//                sex = 1;
//            else
//                sex = 2;
//
//            SysUser user = userDao.queryByOneUser(tempPhone);
//            if (user != null && !StringUtils.isNull(user.getPassword())) {
//                password = user.getPassword().substring(8,24).toUpperCase();
//            }
//
//            /**查询ERP账号是否存在**/
//            String erpSql = "select ID,UserName,LoginName from sys_user_t where LoginName = '" + tempPhone + "' and IsValid = 1";
//            List<Map<String, Object>> userList = jdbcTemplate.queryForList(erpSql);
//            if (userList == null || userList.size() == 0) {
//                String newSql = "insert into sys_user_t (UserName,Loginname,password,male,sys_dept_id,sys_role_id," +
//                        "sys_post_id,status,creatorid,creationtime,remarks,isvalid,empkind,ReviseTime) \n" +
//                        " values (?,?,?,?,1,10,0,2,1,?,?,1,0,?)";
//                Object[] obj = {name, tempPhone, password, sex, new Date(), "", new Date()};
//                jdbcTemplate.update(newSql, obj);
//            } else {
//                continue;
////                Map<String, Object> tempMap = userList.get(0);
////                String updateSql = "update sys_user_t set password = ? , LoginName = ?, ReviseTime = ?, status = ? where id = ?";
////                Object[] obj = {password, tempPhone, new Date(), 2, tempMap.get("ID")};
////
////                jdbcTemplate.update(updateSql, obj);
//            }
//        }
//        updateSql = "update sys_user_t set password = ? , LoginName = ?, ReviseTime = ?, status = ? where UserName = ?";
//        String password = AESCoder.md5("117196").substring(8,24).toUpperCase();
//        Object[] obj = {password, "17843848410", new Date(), 2, "曾号"};
//        jdbcTemplate.update(updateSql, obj);
//
//
//        updateSql = "update sys_user_t set password = ? , LoginName = ?, ReviseTime = ?, status = ? where UserName = ?";
//        password = AESCoder.md5("258038").substring(8,24).toUpperCase();
//        obj = new Object[]{password, "15826076065", new Date(), 2, "万俊杰"};
//        jdbcTemplate.update(updateSql, obj);
        return 0;
    }

    public static void main(String[] args){
        String sq = "500383198810094312";
        System.out.println(sq.substring(6, 10) + "-" + sq.substring(10, 12) + "-" + sq.substring(12, 14));
    }

    /**
     * 同步OA通讯录
     * @return
     */
    public Integer synUser() {
        /**同步OA通讯录系统sql**/
        return 0;
    }

    /**
     * 根据条件查询所有的数据
     * @param user
     * @return
     */
    public List<SysUser> findAll(SysUser user) {
        QueryWrapper<SysUser> query = new QueryWrapper();
        query.eq("status",StateEnum.ENABLED.getCode());
        if(user != null){
        	if(StringUtils.isNotBlank(user.getName())){
        		query.like("name",user.getName());
			}
        	if(StringUtils.isNotBlank(user.getPhone())){
        		query.like("phone",user.getPhone());
			}
		}
        List<SysUser> list = userDao.selectList(query);
        return list;
    }

    /**
     * 查询关联用户
     * @param uid 用户ID
     * @param oid 部门ID
     * @param type 部门类型 0:集团公司，1：部门，2：工厂
     * @param status 状态(0：启用，1：禁用)
     * @return
     */
    public List<Map<String, Object>> queryRelation(Long uid, Integer type, Long oid, Integer status) {
        if (StringUtils.isNull(uid))
            return null;

        if (StringUtils.isNull(type) || type == -1)
            type = null;

        return userDao.queryRelation(uid, type, oid, status);
    }

    /**
     * 分页查询数据
     * @param offset 分页开始位置
     * @param limit 分页大小
     * @return
     */
    public IPage findByPage(String username, String name, Integer status, Integer offset, Integer limit) {
        QueryWrapper<SysUser> query = new QueryWrapper();
        if (!StringUtils.isNull(username))
            query.like("username", username);
        if (!StringUtils.isNull(name))
            query.like("name", name);
        if (!StringUtils.isNull(status))
            query.eq("status", status);

        PageHelper.offsetPage(offset, limit);

        IPage<SysUser> iPage = userDao.selectPage(new Page(offset, limit), query);
        if (iPage != null && iPage.getRecords() != null && iPage.getRecords().size() > 0) {
            PageInfo pageInfo = new PageInfo(iPage.getRecords());
            iPage.setTotal(pageInfo.getTotal());
            /**获取所有用户信息**/
            List<SysUser> list = iPage.getRecords();
            List<SysUser> resultList = new ArrayList<>();
            for (Integer i = 0; i < list.size(); i++) {
                SysUser user = list.get(i);
                /**查询所属部门**/
                List<Map<String, Object>> orgList = userDao.queryOrigin(user.getId(), 2);
                if (orgList != null && orgList.size() > 0) {
                    Boolean slat = true;
                    for (Map<String, Object> map : orgList) {
                        if (slat) {
                            slat = false;
                            user.setRemark(map.get("originName") + ",");
                        } else {
                            user.setRemark(user.getRemark() + map.get("originName") + ",");
                        }
                    }
                    user.setRemark(user.getRemark().substring(0, user.getRemark().length() - 1));
                }
                resultList.add(user);
            }
            iPage.setRecords(resultList);
        }

        return iPage;
    }

    /**
     * 用户关联部门
     * @param uid 用户ID
     * @param orgId 部门ID
     * @return
     */
    public Integer saveRelationOrigin(Long uid, Long orgId) {
            return -1;
    }

    /**
     * 删除关联部门
     * @param uid 用户ID
     * @param orgId 部门ID
     * @return
     */
    public Integer deleteRelationOrigin(Long uid, Long orgId) {
        return -1;
    }

	public Integer deleteRelationOrigin(Long uid){
		return -1;
	}

    /**
     * 新增数据
     * @param user page
     * @return
     */
    public Integer saveInit(SysUser user) {
		return -1;
    }

    /**
     * 更新数据
     * @param dto page
     * @return
     */
    public Integer update(SysUser dto) {
		return -1;
    }

    /**
     * 修改密码
     * @param oldPwd 旧密码
     * @param newPwd 新密码
     * @return
     */
    public Integer updatePwd(Long id, String oldPwd, String newPwd, Integer type) {
		return -1;
    }

    /**
     * 禁用用户
     * @param id 用户ID
     * @param status 用户状态
     * @return
     */
    public Integer updateStatus(Long id, Integer status) {
            return -1;
    }

    /**
     * 根据姓名查询用户
     * @param name
     * @return
     */
    public SysUser queryByName(String name) {
        if (StringUtils.isNull(name))
            return null;

        return userDao.queryByName(name);
    }


    /**
     * 查询员工生日信息
     * @param today
     * @return
     */
    public List<SysUser> queryBirthdayUser(String today) {
		return null;
    }

	@Override
	public synchronized Long getMaxId() {
    	QueryWrapper<SysUser> qu = new QueryWrapper<>();
    	qu.orderByDesc("id");
		QueryWrapper<SysUser> last = qu.last("limit 1");
		SysUser sysUser = userDao.selectOne(last);
		if(sysUser != null){
			Long id = sysUser.getId();
			return id;
		}else {
			return 0l;
		}
	}

	@Override
	public List<SysUser> queryUsersByOrgPos(Long orgId, Long posId,Integer isDefault) {
    	List<SysUser> users = userDao.queryUsersByOrgPos(orgId,posId,isDefault);
		return users;
	}

	// 绑定用户岗位

	@Override
	public Integer savePosition(Long uid, Long orgId, Long posId, Integer isDefault) {
		return -1;
	}

	// 删除用户岗位
	@Override
	public Integer deletePosition(Long uid, Long orgId, Long posId) {
		return -1;
	}

	@Override
	public List<SysUser> findUsersByLeader(Long orgId, Long leaderId) {
		return null;
	}

	@Override
	public List<SysUser> findSubUser(SysUser leader, String userName) {
		return null;
	}

	@Override
	public List<SysUser> findUserByClock(Long deptId, Date sDate, Date eDate) {
		return null;
	}


	@Override
	public List<SysUser> queryByOrgAndPosV3(Long orgId, String... posList) {
		List<SysUser> users = userDao.queryByOrgAndPosV3(orgId, posList);
		return users;
	}
}
